package io.renren.modules.pinKao.controller;

import io.renren.common.annotation.Login;
import io.renren.common.utils.R;
import io.renren.common.config.ListPageUtils;
import io.renren.modules.order.controller.OrderController;
import io.renren.modules.order.entity.OrderEntity;
import io.renren.modules.pinKao.entity.PinKaoAndOrder;
import io.renren.modules.pinKao.entity.PinKaoCourse;
import io.renren.modules.pinKao.entity.PinKaoTeam;
import io.renren.modules.sys.controller.JPushController;
import io.renren.modules.sys.entity.*;
import io.renren.modules.pinKao.service.PinKaoService;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("api/pinkao")
public class PinKaoController {

    @Autowired
    PinKaoService pinKaoService;

    @Autowired
    TokenService tokenService;

    @Autowired
    UserService userService;

    @Autowired
    JPushController jPushController;

    @Autowired
    OrderController orderController;

    /**
     * 发起拼考
     */
    @PostMapping("launchPinKao")
    @Login
    public R launchPinKao(@RequestBody PinKaoAndOrder pinKaoTeam){
        Long userId = tokenService.getUserIdByToken(pinKaoTeam.getToken());
        UserEntity user = userService.getUserByUserId(userId);
        //当课程过期时 不能再发起拼考和加入拼考了
        Map map2 = new HashMap();
        map2.put("courseId",pinKaoTeam.getPinKaoCourseId());
        PinKaoCourse p =pinKaoService.getPinKaoCourseInfo(map2);
        if(p == null){
            return R.error(102,"对不起，这个课程已过期不能发起拼考了哦~");
        }
        //System.out.println(user.getHeadImg());
        pinKaoTeam.setPinKaoTeamImg(user.getHeadImg());
        pinKaoTeam.setUserIds(userId.toString());
        pinKaoTeam.setNickNamesB(user.getNickNameB());  //将昵称B设置为昵称的字节类型
        pinKaoTeam.setNickNames("");  //将昵称设置为空
        pinKaoTeam.setPinKaoTeamCount(1);  //发起拼考时这个拼考团人数是1

        pinKaoService.launchPinKao(pinKaoTeam);

        //加入拼考成功后 需要将订单改成已付款的
        OrderEntity o = new OrderEntity();
        o.setStatus("已付款");
        o.setOrderId(pinKaoTeam.getOrderId());
        orderController.updateOrder(o);

        addPinKaoCourseCount(pinKaoTeam.getPinKaoCourseId(),1);  //拼考课程的拼考人数+1

        //设置自己有这个拼考的单子 pin_kao_user

        //System.out.println(pinKaoTeam.getPinKaoTeamId());
        PinKaoTeam pinKaoTeam1 = pinKaoService.getPinKaoTeamByUserIds(userId.toString());

        Map map = new HashMap();
        map.put("pinKaoUserId",Integer.valueOf(userId.toString()));
        map.put("pinKaoNickName","");
        map.put("pinKaoNickNameB",pinKaoTeam.getNickNamesB());
        map.put("pinKaoCourseId",pinKaoTeam.getPinKaoCourseId());
        map.put("pinKaoTeamId",pinKaoTeam1.getPinKaoTeamId());
        map.put("state",1);
        pinKaoService.insertPinKaoUserInfo(map);
        return R.ok("成功发起拼考！",100);
    }


    /**
     * 获取拼考课程信息
     */
    @PostMapping("getPinKaoCourseInfo")
    public R getPinKaoCourseInfo(@RequestBody Map map){
        int courseId = Integer.valueOf(map.get("courseId").toString());
        PinKaoCourse course = pinKaoService.getPinKaoCourseInfoByCourseId(courseId);

        //List list = new ArrayList();
       String[] list =  course.getCoverImgs().split(";");
       course.setCoverImgs("");
        course.setPicList(list);

        //int courseId = Integer.valueOf(map.get("courseId").toString());
        int count = pinKaoService.getPinKaoCourseTeamCount(courseId);
        course.setTeamCount(count);

        //Long startLong = course.getStartTime().getTime();
        Long endLong = course.getEndTime().getTime();
        Date d = new Date();
        Long time = d.getTime();
        //计算时间差,单位毫秒
        Long ms = endLong-time;
        if(ms <= 0){
            //时间到了 所以拼考的课程就结束了  state设置为0
            pinKaoService.updateStateByCourseId(courseId);
            ms = Long.valueOf(0);
        }
        course.setRemainingTime(ms);

        return R.ok("",100).put("data",course);
    }

    /**
     * 课程的拼考数+1 或者 -1
     */
    public void addPinKaoCourseCount(int courseId,int type){
        if(type == 1){
            pinKaoService.addPinKaoCourseCount(courseId);
        }else{
            pinKaoService.delPinKaoCourseCount(courseId);
        }

    }


    /**
     * 拼考团的人数加减1
     */
    public void addPinKaoTeamCount(int teamId,int type){
        if(type == 1){
            pinKaoService.addPinKaoTeamCount(teamId);
        }else{
            pinKaoService.delPinKaoTeamCount(teamId);
        }
    }



    /**
     * 加入拼考
     */
   @PostMapping("joinPinKao")
   @Login
    public R joinPinKao(@RequestBody Map map){
       Long userId = tokenService.getUserIdByToken(map.get("token").toString());
       int teamId = Integer.valueOf(map.get("pinKaoTeamId").toString());
        PinKaoTeam pinKaoTeam =  pinKaoService.getPinKaoTeamByTeamId(teamId);  //获取到要拼的团

       if(pinKaoTeam.getPinKaoTeamCount() ==  pinKaoTeam.getPinKaoTeamClassification()){
           //满员的时候 修改这个拼考团的状态
           pinKaoService.updateIsSuccessByTeamId(pinKaoTeam.getPinKaoTeamId());
           return R.error(101,"拼考团满啦！去看看其他的拼考团吧~");  //拼考团满了 不能加入
       }

       map.put("courseId",pinKaoTeam.getPinKaoCourseId());
      //课程过期时 不能再加入拼考或者发起拼考了
       PinKaoCourse p = pinKaoService.getPinKaoCourseInfo(map);
       if(p == null){
           return R.error(102,"对不起，这个课程已过期不能再拼了哦~");
       }
       if(pinKaoTeam == null){
           return R.error(102,"对不起，这个团已经过期了哦~");
       }
       //判断是否在团中  不可以拼多个
       String userIds = pinKaoTeam.getUserIds();
       String[] strs = userIds.split(",");
       for(int i = 0;i<strs.length;i++){
           if(strs[i].equals(userId.toString())){
               return R.error(102,"您已经在拼考团中了哦~");
           }
       }

       String newUserIds = pinKaoTeam.getUserIds()+","+userId;  //拼接userId 将新的userIds修改到数据库中
       map.put("userIds",newUserIds);
       //加入拼考
       pinKaoService.joinPinKao(map);  //修改那条数据的参与的人的ids字符串 中间用“，”分割
       //todo 修改订单状态
       //加入拼考成功后 需要将订单改成已付款的
       OrderEntity o = new OrderEntity();
       o.setStatus("已付款");
       String orderId = (String) map.get("orderId");
       o.setOrderId(orderId);
       orderController.updateOrder(o);


       addPinKaoTeamCount(teamId,1);   // 同时参与的这个拼考团的参与人数加1
       addPinKaoCourseCount(pinKaoTeam.getPinKaoCourseId(),1);  // 同时本条课程的拼团人数+1

       UserEntity userEntity = userService.getUserByUserId(userId);

       //参与完成后 pin_kao_user表中加入这条数据
       Map maps = new HashMap();
       maps.put("pinKaoUserId",Integer.valueOf(userId.toString()));
       maps.put("pinKaoNickName","");
       maps.put("pinKaoNickNameB",userEntity.getNickNameB());
       maps.put("pinKaoCourseId",pinKaoTeam.getPinKaoCourseId());
       maps.put("pinKaoTeamId",pinKaoTeam.getPinKaoTeamId());
       maps.put("state",1);
       pinKaoService.insertPinKaoUserInfo(maps);

       //再获取一次这个拼考团 查看这个拼考团的人数是否达到了这个拼考团的类型
       PinKaoTeam newPinKaoTeam =  pinKaoService.getPinKaoTeamByTeamId(teamId);
      if(newPinKaoTeam.getPinKaoTeamCount() ==  newPinKaoTeam.getPinKaoTeamClassification()){
           //如果加入这个人后这个拼考团满了 修改拼考团的状态为0 解散这个拼考团 进行发货
           pinKaoService.updateIsSuccessByTeamId(teamId);

           /*//todo 团满了 应该是订单交易完成 准备发货 修改order的status
            newPinKaoTeam.getPinKaoTeamType();  //学习班  类型
            newPinKaoTeam.getPinKaoCourseId();  //  类型+值+userId*/

           //减去这个拼考课程的正在拼单数量
           int count = pinKaoTeam.getPinKaoTeamClassification();
           Map m = new HashMap();
           m.put("count",count);
           m.put("courseId",pinKaoTeam.getPinKaoCourseId());
           pinKaoService.updateCourseCount(m);

           //修改user表中的订单状态
           String userIdd = newPinKaoTeam.getUserIds();
           String[] userIdds = userIdd.split(",");
           for(int i = 0;i<userIdds.length;i++){
               pinKaoService.updateStateByTeamId(teamId);
           }
           return R.ok("拼考团拼考成功！该拼考团已满,仓库会抓紧发货请耐心等待",100);
       }
       return R.ok("成功加入",100).put("missPeople",newPinKaoTeam.getPinKaoTeamClassification()-newPinKaoTeam.getPinKaoTeamCount());
   }


    /**
     * 获取课程的拼考团列表
     */
    @PostMapping("getPinKaoTeamsByCourse")
    public R getPinKaoTeamsByCourse(@RequestBody Map map){
       List list =  pinKaoService.getPinKaoTeamsByCourse(map);
       if(list.size()!=0){
           for(int i = 0;i<list.size();i++){
               PinKaoTeam p = (PinKaoTeam)list.get(i);
               if(p.getNickNamesB()!= null){
                   p.setNickNames(new String(p.getNickNamesB()));
               }
               if(p.getPinKaoTeamEndTime() != null && p.getPinKaoTeamCreateTime() != null){
                   Date now = new Date();
                   Long time =(p.getPinKaoTeamEndTime().getTime())- (now.getTime());
                   p.setRemainingTime(time);
                   if(time <= 0){
                       //时间为0的时候代表这个团到期了 解散这个团
                        pinKaoService.updateIsSuccessByTeamId(p.getPinKaoTeamId());

                        //todo 解散这个团的时候 所有的order应该是交易关闭的
                   }
               }
               p.setMissPeople(p.getPinKaoTeamClassification()-p.getPinKaoTeamCount());  //返回还差几人拼成此单
           }
       }
       return R.ok("",100).put("data",list);
    }


    /**
     * 返回拼考团的用户列表
     */
    @PostMapping("getUsersInTeam")
    public R getUsersInTeam(@RequestBody Map map){
        //List list = pinKaoService.getUsersInTeam(map);
        List<String> ls = new ArrayList<>();   //这个是已经拼考的人的头像列表  为显示用 真正下单的时候是看里面的id
        //获取这个拼考团
       PinKaoTeam pinKaoTeam =  pinKaoService.getPinKaoTeamByTeamId(Integer.valueOf(map.get("teamId").toString()));
       if(pinKaoTeam == null){
           //没有这个拼考团
           return R.error(102,"拼考团已经解散了哦~");
       }
       String userIds = pinKaoTeam.getUserIds();
       String[] userIdss = userIds.split(",");
       for(int i = 0;i<userIdss.length;i++){
           String userId = userIdss[i];  //获取已经拼考的人的id
           String headImg = userService.getUserByUserId(Long.valueOf(userId)).getHeadImg();
           if(";".equals(headImg.substring(headImg.length()-1,headImg.length()))){
               headImg = headImg.substring(0,headImg.length()-1);
           }
           ls.add(headImg);
       }
       return R.ok("",100).put("data",ls);
    }


    /**
     * 退出拼考团
     */
    /*@PostMapping("exitPinKao")
    public R exitPinKao(@RequestBody Map map){
        Long userId = tokenService.getUserIdByToken(map.get("token").toString());
        int teamId = Integer.valueOf(map.get("teamId").toString());
        Map userMap = new HashMap();
        userMap.put("userId",userId);
        userMap.put("teamId",teamId);
        PinKaoUser pinKaoUser = pinKaoService.getPinKaoUserByUserAndTeamId(userMap);  //获取到这个拼考人的拼考信息
        if(pinKaoUser == null){
            //不存在这个拼考信息 说明没有在这个团中
            return R.error(102,"您没有在这个团中哦");
        }

        map.put("userId",userId);
        pinKaoService.exitPinKao(map);   //在pin_kao_user中将数据先修改掉

        //再获取这个拼考团 判断退出后这个拼考团的人数为几 为0时解散
        PinKaoTeam pinKaoTeam = pinKaoService.getPinKaoTeamByTeamId(teamId);
        if(pinKaoTeam.getPinKaoTeamCount()<= 1){
            //拼考团的人数为1 说明这个拼考团就这一个人了  解散这个拼考团
            pinKaoService.updateIsSuccessByTeamId(teamId);
            return R.ok("拼考团已解散",100);
        }else{
            //拼考团还有其他人  修改userIds
            String userIds = pinKaoTeam.getUserIds();
            String strUserId = userId.toString();

            String[] strs = userIds.split(",");
            if(strs[0].equals(strUserId)){
                //说明是第一个人要退出 切掉userId+","
                strs[0].replace(userId+",","");
            }
            //不是第一个人  要切掉","+userId
            userIds.replace(strUserId+"","");
            System.out.println(userIds);
            }
            addPinKaoTeamCount(teamId,2);  //减少一位拼考团成员数量
            return R.ok("退出拼考团成功",100);
        }*/


    /**
     * 根据课程分类获取课程
     */
    @PostMapping("getPinKaoCourseByClassification")
    public R getPinKaoCourseByClassification(@RequestBody Map map){
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        List courseList = pinKaoService.getPinKaoCourseByClassification(map);
        /*for(int i = 0;i<courseList.size();i++){
            PinKaoCourse pinKaoCourse = (PinKaoCourse) courseList.get(i);
            String coverImgs = pinKaoCourse.getCoverImgs();
            if(coverImgs != null && "".equals(coverImgs)){
                String[] imgList = coverImgs.split(";");
                pinKaoCourse.setCoverImg(imgList[0]);
            }
        }*/
        if(courseList.size()>0){
            ListPageUtils pageUtil = new ListPageUtils(courseList,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                return R.ok("",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("",100).put("data",courseList).put("nextNum",-1);
    }
    }

